﻿
// MainProgramDlg.cpp: 实现文件
//

#include "pch.h"
#include "framework.h"
#include "MainProgram.h"
#include "MainProgramDlg.h"
#include "afxdialogex.h"
#include "string"
#include <iostream>
#include <chrono>
#include <thread>
#include <mutex>
//#include "myQtLib.h"
//#include "global.h"
#include <map>

#ifdef _DEBUG
#define new DEBUG_NEW
#endif


// 用于应用程序“关于”菜单项的 CAboutDlg 对话框

class CAboutDlg : public CDialogEx
{
public:
	CAboutDlg();

// 对话框数据
#ifdef AFX_DESIGN_TIME
	enum { IDD = IDD_ABOUTBOX };
#endif

	protected:
	virtual void DoDataExchange(CDataExchange* pDX);    // DDX/DDV 支持

// 实现
protected:
	DECLARE_MESSAGE_MAP()
};

CAboutDlg::CAboutDlg() : CDialogEx(IDD_ABOUTBOX)
{
}

void CAboutDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialogEx::DoDataExchange(pDX);
}

BEGIN_MESSAGE_MAP(CAboutDlg, CDialogEx)
END_MESSAGE_MAP()


// CMainProgramDlg 对话框



CMainProgramDlg::CMainProgramDlg(CWnd* pParent /*=nullptr*/)
	: CDialogEx(IDD_MAINPROGRAM_DIALOG, pParent)
{
	m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
}

void CMainProgramDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialogEx::DoDataExchange(pDX);
}

BEGIN_MESSAGE_MAP(CMainProgramDlg, CDialogEx)
	ON_WM_SYSCOMMAND()
	ON_WM_PAINT()
	ON_WM_QUERYDRAGICON()
	ON_BN_CLICKED(IDC_OPENFILE, &CMainProgramDlg::OnBnClickedOpenfile)
	ON_BN_CLICKED(IDOK, &CMainProgramDlg::OnBnClickedOk)
END_MESSAGE_MAP()


// CMainProgramDlg 消息处理程序

BOOL CMainProgramDlg::OnInitDialog()
{
	CDialogEx::OnInitDialog();

	// 将“关于...”菜单项添加到系统菜单中。

	// IDM_ABOUTBOX 必须在系统命令范围内。
	ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX);
	ASSERT(IDM_ABOUTBOX < 0xF000);

	CMenu* pSysMenu = GetSystemMenu(FALSE);
	if (pSysMenu != nullptr)
	{
		BOOL bNameValid;
		CString strAboutMenu;
		bNameValid = strAboutMenu.LoadString(IDS_ABOUTBOX);
		ASSERT(bNameValid);
		if (!strAboutMenu.IsEmpty())
		{
			pSysMenu->AppendMenu(MF_SEPARATOR);
			pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu);
		}
	}

	// 设置此对话框的图标。  当应用程序主窗口不是对话框时，框架将自动
	//  执行此操作
	SetIcon(m_hIcon, TRUE);			// 设置大图标
	SetIcon(m_hIcon, FALSE);		// 设置小图标

	// TODO: 在此添加额外的初始化代码

	return TRUE;  // 除非将焦点设置到控件，否则返回 TRUE
}

void CMainProgramDlg::OnSysCommand(UINT nID, LPARAM lParam)
{
	if ((nID & 0xFFF0) == IDM_ABOUTBOX)
	{
		CAboutDlg dlgAbout;
		dlgAbout.DoModal();
	}
	else
	{
		CDialogEx::OnSysCommand(nID, lParam);
	}
}

// 如果向对话框添加最小化按钮，则需要下面的代码
//  来绘制该图标。  对于使用文档/视图模型的 MFC 应用程序，
//  这将由框架自动完成。

void CMainProgramDlg::OnPaint()
{
	if (IsIconic())
	{
		CPaintDC dc(this); // 用于绘制的设备上下文

		SendMessage(WM_ICONERASEBKGND, reinterpret_cast<WPARAM>(dc.GetSafeHdc()), 0);

		// 使图标在工作区矩形中居中
		int cxIcon = GetSystemMetrics(SM_CXICON);
		int cyIcon = GetSystemMetrics(SM_CYICON);
		CRect rect;
		GetClientRect(&rect);
		int x = (rect.Width() - cxIcon + 1) / 2;
		int y = (rect.Height() - cyIcon + 1) / 2;

		// 绘制图标
		dc.DrawIcon(x, y, m_hIcon);
	}
	else
	{
		CDialogEx::OnPaint();
	}
}

//当用户拖动最小化窗口时系统调用此函数取得光标
//显示。
HCURSOR CMainProgramDlg::OnQueryDragIcon()
{
	return static_cast<HCURSOR>(m_hIcon);
}

void CMainProgramDlg::OnBnClickedOpenfile()
{
	CString sFilter(_T("文件（pc,k）|*.pc;*.k|"));
	CFileDialog fdlg(TRUE, NULL, NULL, OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT | OFN_ALLOWMULTISELECT | OFN_NOCHANGEDIR, sFilter, NULL, 0, FALSE);
	const int MAX_FILES = 1;//至多选择1个文件
	fdlg.m_ofn.lpstrFile = new TCHAR[MAX_PATH * MAX_FILES];
	fdlg.m_ofn.nMaxFile = MAX_PATH * MAX_FILES;
	memset(fdlg.m_ofn.lpstrFile, 0, sizeof(TCHAR) * fdlg.m_ofn.nMaxFile);
	CString sPath;
	if (fdlg.DoModal() == IDOK)
	{
		POSITION pos = fdlg.GetStartPosition();

		while (NULL != pos)
		{
			m_sPathName = fdlg.GetNextPathName(pos);
			sPath = m_sPathName;
			CString sFileName = PathFindFileName(m_sPathName);
			sPath.Replace(sFileName, _T(""));
		}
	}
	delete[] fdlg.m_ofn.lpstrFile;

}

using namespace modelanalysis;
typedef ModelAnalysis* (_cdecl* GetAnalysisGeneraterFun2)();
static HINSTANCE s_hmod = NULL;
static GetAnalysisGeneraterFun2 s_pAnalysisGenerateFun = NULL;
typedef void(_cdecl* GetReleaseGenerateFun2)(ModelAnalysis*);
typedef void (*SHOWCONSOLE)();

ModelAnalysis* getAnalysisGenerater2()
{
	if (!s_pAnalysisGenerateFun)
	{
		if (s_hmod == NULL)
		{
			std::string sDllFile;
			sDllFile = "ModelAnalysis.dll";
			s_hmod = ::LoadLibraryA(sDllFile.c_str());//载入指定的动态链接库，并将其映射到当前使用地址空间.
		}
		if (s_hmod == NULL)
		{
			printf("加载ModelAnalysis.dll失败");
			return NULL;
		}
		if (s_hmod != NULL)
		{
			SHOWCONSOLE ShowConsoleFunc = (SHOWCONSOLE)GetProcAddress(s_hmod, "ShowConsole");
			if (ShowConsoleFunc != NULL)
			{
				ShowConsoleFunc(); // 调用DLL中的函数来显示控制台
				printf("这是DLL中的控制台窗口！\n");
				system("pause"); // 保持窗口打开直到用户按下键
			}
		}
		s_pAnalysisGenerateFun = (GetAnalysisGeneraterFun2)GetProcAddress(s_hmod, "getAnalysisGenerater");//检索在DLL中输出函数地址.
	}
	if (!s_pAnalysisGenerateFun)
		return NULL;
	

	return s_pAnalysisGenerateFun();
}

char* CstringToChar(CString str)
{
	/*char* buf=new char[10];*/
	int len = WideCharToMultiByte(CP_ACP, 0, str, -1, NULL, 0, NULL, NULL);
	char* buf = new char[len + 1];
	WideCharToMultiByte(CP_ACP, 0, str, -1, buf, len, NULL, NULL);
	return buf;
}

void CMainProgramDlg::OnBnClickedOk()
{
	//获取接口对象
	m_pGenerate = getAnalysisGenerater2();
	if (!m_pGenerate)
		return;
	m_pGenerate->Initialize();
	const char* cPath = CstringToChar(m_sPathName);
	
	// 带进度回调的用法
	auto progressCallback = [](const std::string& file, int line, const std::string& content) 
	{
		std::cout << "[跟踪] 正在读取: " << file << ":" << line
			<< " -> " << (content.length() > 20 ? content.substr(0, 17) + "..." : content) << "\n";
	};

	try 
	{
		// 读取主文件（支持自定义包含前缀）
		m_pGenerate->readFile(cPath, progressCallback);
	}
	catch (const std::exception& e) {
		std::cerr << "错误: " << e.what() << std::endl;
	}
	
	m_pGenerate->unInitialize();
	//释放接口
	if (s_hmod)
	{
		GetReleaseGenerateFun2 pReleaseFun = (GetReleaseGenerateFun2)GetProcAddress(s_hmod, "releaseAnalysisGenerate");
		if (pReleaseFun)
			pReleaseFun(m_pGenerate);
	}
	m_pGenerate = NULL;

	//共享数据
	std::map<double, double> data;


	CDialogEx::OnOK();
}
